package com.greet.controller.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.greet.constant.RedisDataKeys;
import com.greet.context.BaseContext;
import com.greet.dto.OrdersDTO;
import com.greet.dto.OrdersPageQueryDTO;
import com.greet.dto.OrdersPaymentDTO;
import com.greet.dto.OrdersSubmitDTO;
import com.greet.entity.Orders;
import com.greet.result.PageResult;
import com.greet.result.Result;
import com.greet.service.OrderService;
import com.greet.vo.*;
import com.greet.websocket.WebSocketServer;
import io.jsonwebtoken.Claims;
import jakarta.websocket.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;


@RestController("userOrderController")
@RequestMapping("/user/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private WebSocketServer webSocketServer;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/submit")
    public Result<OrderSubmitVO> submit(@RequestBody OrdersSubmitDTO ordersSubmitDTO){
        OrderSubmitVO orderSubmitVO = orderService.submit(ordersSubmitDTO);
        return Result.success(orderSubmitVO);
    }

    @PutMapping("/payment")
    public Result<OrderPaymentVO> payment(@RequestBody OrdersPaymentDTO paymentDTO){
        //调用支付
        Long orderId = orderService.payment(paymentDTO);
        //支付成功调用使用websocket向管理端发送提示信息
        //三个字段 type orderId content
        Map map = new HashMap<>();
        map.put("type", 1); //1表示来单提醒，2表示客户催单
        map.put("orderId", orderId);
        map.put("content", "您有新的订单(订单号:" + paymentDTO.getOrderNumber() + ")");
        String jsonString = JSON.toJSONString(map);
        Collection<Session> values = WebSocketServer.getSessionMap().values();
        for (Session session : values){
            webSocketServer.sendToClient(jsonString, session);
        }

        return Result.success(OrderPaymentVO.builder().build());
    }

    @GetMapping("/orderDetail/{id}")
    public Result<OrderVO> getById(@PathVariable Long id){
        OrderVO orderVO = orderService.getById(id);
        return Result.success(orderVO);
    }

    @GetMapping("/historyOrders")
    public Result<PageResult> historyOrders(OrdersPageQueryDTO ordersPageQueryDTO){
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        Integer index = (ordersPageQueryDTO.getPage() - 1) * ordersPageQueryDTO.getPageSize();
        ordersPageQueryDTO.setPage(index);
        PageResult pageResult = orderService.historyOrders(ordersPageQueryDTO);
        return Result.success(pageResult);
    }

    @PostMapping("repetition/{id}")
    public Result repetition(@PathVariable Long id){
        Integer status = (Integer) redisTemplate.opsForValue().get(RedisDataKeys.SHOP_STATUS);
        if (status == 0)return Result.error("店铺已经打烊啦!");
        orderService.repetition(id);
        //支付成功调用使用websocket向管理端发送提示信息
        //三个字段 type orderId content
        OrderVO orderVO = orderService.getById(id);
        Map map = new HashMap<>();
        map.put("type", 1); //1表示来单提醒，2表示客户催单
        map.put("orderId", id);
        map.put("content", "您有新的订单(订单号:" + orderVO.getNumber() + ")");
        String jsonString = JSON.toJSONString(map);
        Collection<Session> values = WebSocketServer.getSessionMap().values();
        for (Session session : values){
            webSocketServer.sendToClient(jsonString, session);
        }
        return Result.success();
    }

    @PutMapping("/cancel/{id}")
    public Result cancel(@PathVariable Long id){
        orderService.cancel(id);
        return Result.success();
    }

    @GetMapping("/reminder/{id}")
    public Result reminder(@PathVariable Long id){
        if (redisTemplate.hasKey("reminder_" + id)){
            return Result.error("已经催过单了，过一段时间再试试吧");
        }
        redisTemplate.opsForValue().set("reminder_" + id, id, Duration.ofMinutes(10L));

        OrderVO orderVO = orderService.getById(id);
        Map map = new HashMap<>();
        map.put("type", 2); //1表示来单提醒，2表示客户催单
        map.put("orderId", id);
        map.put("content", "客户催单(订单号:" + orderVO.getNumber() + ")");
        String jsonString = JSON.toJSONString(map);
        Collection<Session> values = WebSocketServer.getSessionMap().values();
        for (Session session : values){
            webSocketServer.sendToClient(jsonString, session);
        }
        return Result.success();
    }

}
